<!--
* description: 二级联动下拉框-调API取值
* author: tfy
* createdDate: 2019-10-11
* modify: zxuan 2019-10-28
-->
<template>
  <section>
    <el-col :span="span">
      <div class="comwidth">
        <lableName
          :validrule="validrule"
          :curLabelName="curLabelName"
          :isShowLabel="isShowLabel"
          :isRequire="isRequire"
        ></lableName>

        <el-select
          :multiple="isMul"
          :multiple-limit="changeCodeArray[0]&&changeCodeArray[0].limit?changeCodeArray[0].limit:0"
          collapse-tags
          :filterable="filterable"
          v-model="modelCode"
          placeholder="请选择"
          @clear="clearCodeSelect"
          :clearable="clearable"
          @change="sendCode1"
          :disabled="disabled"
          :readonly="readonly"
          size="small"
        >
          <el-option v-if="chackAll" :label="'所有'+curLabelName" value="all"></el-option>
          <el-option
            v-for="item in optionDatas"
            :key="item[codeField]"
            :label="item[textField]"
            :value="item[codeField]"
          >{{item[textField]}}</el-option>
        </el-select>
        <validateFormate :curLabelName="curLabelName" :validrule="validrule"></validateFormate>
      </div>
    </el-col>
  </section>
</template>
<script>
import { crmApis } from "@/api/apiList/crm";
import { requestAPI } from "@/api/commonRequest";
// import lableName from "@/components/lableName";
import { dropdownMixins } from "@/components/mixins/dropdownMixins";
// import validateFormate from "@/components/validateFormate";
export default {
  name: "secondDropList",
  // 组件混入对象：{props[span,isShowLabel,code,isMul,labelName] data[modelCode,optionDatas,listQuery] methods[queryTable,sendCode]}
  mixins: [dropdownMixins],
  components: {
    lableName: () => import("@/components/lableName"), //标题溢出样式组件
    validateFormate: () => import("@/components/validateFormate"), //校验提示样式组件
  },
  props: {
    // 值列表类型编码
    lookuptype: { type: Object, default: {} },
    // 获取组件中的名称，如：textField="carBrandCode"
    codeField: { type: String, default: "lookupValueCode" },
    // 获取组件中的名称，如：textField="carBrandName"
    textField: { type: String, default: "lookupValueName" },
    extralField: {
      type: Array,
      default: function () {
        return [];
      },
    },
    extralParams: {
      type: Object,
      default: function () {
        return {};
      },
    },
    changeCodeArray: {
      type: Array,
      default: function () {
        return [];
      },
    },
    chackAll: {
      type: Boolean,
      default: function () {
        return false;
      },
    },
  },
  data() {
    return {
      optionDatas: [],
      listQuery: this.getListQuery(),
      allModelCode: false,
    };
  },
  watch: {
    modelCode(val, oldval) {
      if (this.chackAll) {
        let newindex = val.indexOf("all"),
          oldindex = oldval.indexOf("all"); //获取val和oldval里all的索引,如果没有则返回-1
        if (newindex != -1 && oldindex == -1) {
          if (this.optionDatas.length === 0) {
            this.modelCode = "";
            return;
          }
          //如果新的选择里有勾选了选择所有 则 勾选所有选项
          this.allModelCode = true;
          this.modelCode = ["all"];
          for (var i in this.optionDatas) {
            this.modelCode.push(this.optionDatas[i][this.codeField]);
          }
        } else if (newindex == -1 && oldindex != -1) {
          //取消勾选所以  则移除掉所有项的勾选
          this.allModelCode = false;
          this.modelCode = [];
        }
        if (val.length < oldval.length && newindex != -1 && this.allModelCode) {
          this.allModelCode = false;
          this.modelCode.splice(this.modelCode.indexOf("all"), 1);
        }
        if (
          val.length == this.optionDatas.length &&
          !this.allModelCode &&
          this.modelCode.length > 0
        ) {
          this.allModelCode = true;
          this.modelCode = ["all"].concat(this.modelCode);
        }
      }
      let str = this.codeField;
      if (str) {
        let queryVal = val.indexOf("all") == -1 ? val : "";
        this.$emit(
          "changeDropValue",
          queryVal,
          "",
          this.codeField,
          this.textField
        );
        this.$emit(
          "changeValuewithSame",
          queryVal,
          "",
          this.codeField,
          this.textField
        );
      }
      this.sendCode1();
    },
  },
  methods: {
    getListQuery() {
      if (this.extralParams) {
        return Object.assign({ isEnable: "1" }, this.extralParams);
      } else {
        return { isEnable: "1" };
      }
    },
    getData: function (val, txt, name, name1, value1, name2, value2) {
      if (typeof val == "string") {
        let that = this;
        let params = {};
        let changCode = "";
        let apiQueryRow = [that.codeField, that.textField];
        if (that.changeCodeArray.length > 0) {
          changCode = that.changeCodeArray[0].changCode;
          params[changCode] = val;
        }
        if (name1) {
          params[name1] = value1;
          changCode = name1;
        }
        if (name2) {
          params[name2] = value2;
        }
        if (that.extralField.length > 0) {
          for (let i = 0; i < that.extralField.length; i++) {
            apiQueryRow.push(that.extralField[i]);
          }
        }
        Object.assign(params, that.listQuery);
        let queryObj = {
          // api配置
          apiConfig: that.lookuptype,
          // 需要调用的API服务配置
          apiServices: [
            {
              //表格中台返回网格的字段
              apiQueryRow: apiQueryRow,
            },
          ],
          //条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
            pageSize: 1000,
            pageIndex: 1,
            //当前中台使用的名称有dataInfo、info，具体查看API文档
            dataInfo: changCode ? params : that.listQuery, //值列表编码
          },
        };
        let paramD = that.$getParams(queryObj);
        // 调用中台API方法（可复用）
        requestAPI(paramD).then((response) => {
          if (response.result == "1") {
            that.optionDatas =
              response.rows;
          }
        });
      }
    },
    sendCode1(value) {
      let val = this.modelCode;
      let text = this.codeField;
      this.$emit("changeCode", val, text);
      this.$emit("getCode", val, text);
      var that = this;
      var option = that.optionDatas;
      let j = value;
      var name = "";
      var extralField = {};
      for (var i = 0; i < option.length; i++) {
        if (option[i][that.codeField] == j) {
          name = option[i][that.textField];
          // extralField = option[i][that.extralField];
          if (that.extralField.length > 0) {
            for (var m = 0; m < that.extralField.length; m++) {
              extralField[that.extralField[m]] = option[i][that.extralField[m]];
            }
          }
          this.$emit("changeExtralField", j, name, extralField);
          //this.$emit("sendChangeCode", j,name);
          this.$emit(
            "changeDropValue",
            j,
            name,
            that.codeField,
            that.textField
          );
        }
      }
      this.sendCode();
      this.$emit("sendChangeCode", val, text, that.textField, name);
    },
    clearCodeSelect() {
      this.sendCode1();
    },
  },
};
</script>
